<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="openDialog"
            >新增角色</el-button>
            <!-- 表格 -->
            <el-table v-loading="isLoading" :data="list">
              <el-table-column
                label="序号"
                type="index"
                width="100"
                :index="indexMethod"
              />
              <el-table-column label="角色名称" prop="name" width="240" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button size="small" type="success" @click="assingPermission(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(row)">编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="delRole(row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              :current-page="page"
              :page-sizes="[5, 10, 15, 20]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>

          <el-tab-pane label="公司信息">
            <!-- 公司信息 -->
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyInfo.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input
                  v-model="companyInfo.companyAddress
                  "
                  disabled
                  style="width:400px"
                />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyInfo.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyInfo.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <el-dialog :title="title" :visible="showDialog" :close-on-click-modal="false" @close="closeDialog">
        <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="form.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>
        <template slot="footer">
          <el-button type="info" size="default" @click="closeDialog()">取消</el-button>
          <el-button type="primary" size="default" @click="confirmAddRole">确认</el-button>

        </template>
      </el-dialog>
      <!-- 分配权限的弹层 -->
      <el-dialog title="分配权限" :visible="showAssignDialog" @open="getPermissionList" @close="closeAssignDialog">
        <!-- show-checkbox 展示复选框 -->
        <!-- check-strictly 复选框不关联 -->
        <el-tree ref="tree" v-loading="treeLoading" :data="permissionList" :props="{label:'name'}" :show-checkbox="true" :check-strictly="false" :default-expand-all="true" node-key="id" />
        <template #footer>
          <div style="text-align: right;">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click="confirmAssign">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRoleListApi, delRoleApi, addRoleApi, editRoleApi, getRoleInfoApi, assignPermissionApi } from '@/api/setting'
import { getCompanyByIdApi } from '@/api/company'
import { getPermissionListApi } from '@/api/permission'
import { transListToTreeData } from '@/utils/index'
export default {
  name: 'Setting',
  data() {
    return {
      page: 1,
      pageSize: 5,
      list: [],
      total: 0,
      isLoading: false,
      showDialog: false,
      form: {
        name: '',
        description: ''
      },
      companyInfo: {},
      rules: {
        name: [
          { required: true, trigger: ['blur'], message: '必填' }
        ],
        description: [
          { required: true, trigger: ['blur'], message: '必填' }
        ]
      },
      showAssignDialog: false,
      roleId: '',
      permissionList: [],
      treeLoading: false // 树状结构加载中
    }
  },
  computed: {
    title() {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  },
  created() {
    this.getRoleList()
    this.getCompanyById()
  },
  methods: {
    /**
     * 点击确定按钮，获取
     */
    async confirmAssign() {
      // 获取勾选的id
      const permIds = this.$refs.tree.getCheckedKeys()
      console.log({ id: this.roleId, permIds: permIds })
      await assignPermissionApi({ id: this.roleId, permIds: permIds })
      this.$message.success('分配权限成功')
      this.closeAssignDialog()
    },
    /**
     * 得到权限列表,回显
     */
    async getPermissionList() {
      const res = await getPermissionListApi()
      this.permissionList = transListToTreeData(res.data, '0')
    },
    /**
     * 点击分配权限按钮获取id,回显
     */
    async assingPermission(id) {
      this.showAssignDialog = true
      this.rowId = id
      this.treeLoading = true
      const { data: { permIds }} = await getRoleInfoApi(this.rowId)
      this.$refs.tree.setCheckedKeys(permIds)
      this.treeLoading = false
    },
    /**
     * 弹框隐藏功能
     */
    closeAssignDialog() {
      this.showAssignDialog = false
    },
    async getRoleList() {
      this.isLoading = true
      const res = await getRoleListApi(this.page, this.pageSize)
      this.isLoading = false
      this.list = res.data.rows
      // console.log(this.list, 'list')
      this.total = res.data.total
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.page = 1
      this.getRoleList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getRoleList()
    },
    indexMethod(row) {
      return (this.page - 1) * this.pageSize + row + 1
    },
    /**
     * 删除方法
     */
    delRole(id) {
      this.$confirm('确认删除？', '提示').then(async() => {
        await delRoleApi(id)
        this.$message.success('删除成功')
        // 判断当前列表的数是否只剩1，是就让page-1,刷新
        if (this.list.length === 1) {
          this.page = this.page - 1
          this.getRoleList()
        }
      })
    },
    openDialog() {
      this.showDialog = true
      this.form = {
        name: '',
        description: '',
        id: ''
      }
    },
    closeDialog() {
      this.showDialog = false
    },
    confirmAddRole() {
      this.$refs.roleForm.validate(async(flag) => {
        if (flag) {
          if (this.form.id) {
            // 有id为修改
            await editRoleApi(this.form)
            this.$message({
              type: 'success',
              message: '修改成功'
            })
          } else {
            // 为添加，发送请求
            await addRoleApi(this.form)
            this.$message({
              type: 'success',
              message: '添加成功'
            })
            // 清空form数据和校验
            this.$refs.roleForm.resetFieleds()
          }
          // 重新获取列表
          this.closeDialog()
          this.getRoleList()
        }
      })
    },
    async editRole(row) {
      // 获取要修改的角色信息并回显
      const res = await getRoleInfoApi(row.id)
      this.form = res.data
      this.showDialog = true
    },
    async getCompanyById() {
      const companyId = this.$store.state.user.userInfo.companyId
      const res = await getCompanyByIdApi(companyId)
      this.companyInfo = res.data
    }
  }
}
</script>

<style scoped lang="sass">
</style>
